package commands

import (
	"errors"
	"strconv"
	"time"

	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Beta - only a publish the beta version
func Beta(config utils.Config) cli.Command {
	return cli.Command{
		Name:     "beta",
		Usage:    "publish the beta version",
		Category: "MANAGER COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
		},
		Action: makeAction(config, betaAction),
	}
}

func betaAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	result, err := utils.LoadConfig(conf, git, "config")
	if err != nil {
		return err
	}
	var info string
	info, err = result.String("session", conf.PcCode)
	if err != nil {
		return errors.New("The Project based in sgbm, please login to publish")
	}
	info, err = result.String("user", info)
	if (err != nil) || (("manager" != info) && ("master" != info)) {
		return errors.New("The Project based in sgbm, please login with manager/master to publish")
	}

	beta, _ := result.String("global", "beta")
	ver, _ := result.String("global", "ver")
	dev, _ := result.String("global", "dev")
	time := time.Now().Unix()

	var VER string
	VER, err = utils.UpdateVersionMiddle(ver)
	if err != nil {
		return err
	}

	_, err = git.Execute(
		[]string{"checkout", dev},
		[]string{"tag", "v" + VER + "." + strconv.FormatInt(time, 10) + "-" + beta},
		[]string{"push", "-u", "origin", "--tags"},
	)
	return err
}
